package com.framework.bdf4j.msg.sender;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.framework.bdf4j.comm.exception.ExceptionUtil;
import com.framework.bdf4j.comm.mail.MailHelper;
import com.framework.bdf4j.msg.constant.PublicConstant;
import com.framework.bdf4j.msg.entity.dto.SysMessagesSaveDTO;
import com.framework.bdf4j.msg.entity.vo.SysMsgResultVO;
import com.framework.bdf4j.msg.entity.vo.SysUserVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 邮件发送器
 *
 * @author shan.deng
 * @date 2020-07-15 16:06:44
 */
@Slf4j
@Component("emailMessageSender")
public class EMailMessageSender  extends Sender{

    @Autowired
    private MailHelper mailHelper;
    
    /**
     * 发送邮件
     * @param sysMessagesSaveDTO
     */
    @Override
    @Async
    public void send(Integer msgId, SysMessagesSaveDTO sysMessagesSaveDTO, List<SysUserVO> users) {
        List<SysMsgResultVO> results = new ArrayList<>();
        users.stream().forEach(user -> {
            SysMsgResultVO resultVO = sendOneByOne(user,sysMessagesSaveDTO.getMsgTitle(),sysMessagesSaveDTO.getMsgContent());
            results.add(resultVO);
        });
        recordResult(msgId,results);
    }

    private SysMsgResultVO sendOneByOne(SysUserVO sysUser,String title,String content) {

        try {
            mailHelper.sendMail(sysUser.getEmail(), title, content);
            log.info("{}邮件发送成功",sysUser.getEmail());
            return new SysMsgResultVO(sysUser.getUserId(), PublicConstant.MSG_SEND_RESULT_SUCCESS_CODE,PublicConstant.MSG_SEND_RESULT_SUCCESS_TEXT,PublicConstant.SEND_TYPE_EMAIL);

        }catch (Exception ex) {
            log.error("邮件发送失败",ex);
            String reason = ExceptionUtil.getExceptionMessage(ex);
            return new SysMsgResultVO(sysUser.getUserId(),PublicConstant.MSG_SEND_RESULT_FAILURE_CODE,reason,PublicConstant.SEND_TYPE_EMAIL);
        }
    }
}
